from fastapi import FastAPI, BackgroundTasks
from pydantic import BaseModel
from trainer import train_svm_model
import uuid
import requests
from predict import router as predict_router
app = FastAPI(title="喜牛牛")

class TrainRequest(BaseModel):
    trainPath: str
    testPath: str
    modeId: int
CALLBACK_URL = "http://localhost:48080/admin-api/happy-ox-core/ox-mode/trainDoneCallBack"
@app.post("/train_svm")
async def train_svm(request: TrainRequest, background_tasks: BackgroundTasks):
    """
    触发训练任务
    """
    # 后台执行（不会阻塞主线程）
    task_id = str(uuid.uuid4())
    background_tasks.add_task(run_training_and_callback, request)
    return {"message": "训练已启动，请稍后等待回调", "taskId": task_id}


def run_training_and_callback(request: TrainRequest):
    """
    后台执行训练任务，并在训练完成后回调 Java 接口
    """
    try:
        print(f"🚀 开始训练: train={request.trainPath}, test={request.testPath}, modeId={request.modeId}")
        result = train_svm_model(request.trainPath, request.testPath)

        # === 封装回调数据 ===
        callback_data = {
            "status": "success",
            "accuracy": str(result["accuracy"]),
            "modeId": request.modeId,
            "modelPath": result["modelPath"],
            "message": "训练完成"
        }

        # === 发起HTTP回调 ===
        print(f"📡 回调 Java 接口: {CALLBACK_URL}")
        response = requests.post(CALLBACK_URL, json=callback_data, timeout=10)
        print("✅ 回调成功:", response.status_code, response.text)

    except Exception as e:
        print("❌ 训练或回调出现错误:", e)

        # === 回调失败状态给 Java ===
        error_callback = {
            "status": "failed",
            "accuracy": "0",
            "modeId": request.modeId,
            "modelPath": "",
            "message": f"训练失败: {str(e)}"
        }

        try:
            requests.post(CALLBACK_URL, json=error_callback, timeout=10)
        except Exception as cb_e:
            print("❌ 二次回调失败:", cb_e)
            

app.include_router(predict_router)